local M = {}
local config = require("colors.config").config
local space = " "

-- styles
-- bold underline undercurl italic reverse
local function highlight(highlights)
	for name, settings in pairs(highlights) do
		local fg = settings.fg and "guifg=" .. settings.fg or "guifg=NONE"
		local bg = settings.bg and "guibg=" .. settings.bg or "guibg=NONE"
		local style = settings.style and "gui=" .. settings.style or "gui=NONE"
		local sp = settings.sp and "guisp=" .. settings.sp or ""
		local gui = space .. style .. space .. fg .. space .. bg .. space .. sp
		if settings.link and (settings.fg == nil and settings.bg == nil and settings.sp == nil) then
			vim.cmd("highlight! link " .. name .. space .. settings.link)
		else
			vim.cmd("highlight " .. name .. gui)
		end
	end
end

---Setup the theme via the default config or the users own
---@param user_config table
---@return table
function M.setup(user_config)
	return require("colors.config").set_config(user_config)
end

---Load the theme
---@return table
function M.load()
	local hl = require("colors.theme")

	vim.cmd("hi clear")
	if vim.fn.exists("syntax_on") then
		vim.cmd("syntax reset")
	end
	vim.o.termguicolors = true
	vim.g.colors_name = config.theme
	highlight(hl.common)
	highlight(hl.syntax)
	highlight(hl.git)
	highlight(hl.treesitter)
	for _, group in pairs(hl.plugins) do
		highlight(group)
	end
	hl.terminal_color()
	local ts = config.options.transparency
	if ts then
		highlight(hl.transparency)
	end
		highlight(hl.statusline)
end

---Get the color table for a specific theme (e.g. onedark/onelight).
---@param theme string
---@return table
function M.get_colors(theme)
	if not theme then
		theme = config.theme
	end

	return require("colors.schemes." .. theme)
end

return M
